<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 *  Menu Controller
 *
 * @package XGO CMS v2.0
 * @subpackage menu
 * @author Manh Nguyen - 06/08/2012
 * @link http://sunsoft.vn
 */
class Menu extends CI_Controller {

    /**
     * Contrust class
     *
     * @access public
     */
    public function __construct() {

        parent::__construct();

		$this->load->library('smarty3', '', 'smarty');
        
        require_once(APPPATH . 'modules/backend/autoload.php');        
        
        $this->load->library('login_manager');
        require_once(APPPATH . 'modules/backend/info.php');

        $this->login_manager->check_role('menu');
        $this->load->language('backend');
        
        $this->smarty->assign('language', $this->lang);
        $this->smarty->assign('message', $this->session->flashdata('message'));
        $this->smarty->assign('error_message', $this->session->flashdata('error_message'));
    }

    /**
     * index function, show jquery grid
     *
     * @access public
     * @param null
     * @return void
     */
    function index() {
        $parameters = $this->uri->ruri_to_assoc();

        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
            if ($id > 0) {
                $this->session->set_userdata('search_id', $id);
            }
        }

        $css_files = array(base_url() . 'data/jscripts/jqgrid/css/ui.jqgrid.css');

        $js_files = array(
            base_url() . 'data/jscripts/jqgrid/i18n/grid.locale-vi.js',
            base_url() . 'data/jscripts/jqgrid/jquery.jqGrid.min.js'
        );

        require_once(APPPATH . 'modules/backend/history.php');
        $menu = new Menu_model();
        
        //load parameters and initialize grid
        $jqgrid = array();

        $jqgrid['id'] = 'jqgrid';
        $jqgrid['pager'] = 'pagered';
        $jqgrid['caption'] = $menu->localize_label('manager');
        $jqgrid['url_metadata'] = site_url($this->router->directory . 'menu/jqgrid_jsoninit');
        $jqgrid['url_data'] = site_url($this->router->directory . 'menu/jqgrid_jsondata');
        $jqgrid['url_create'] = site_url($this->router->directory . 'menu/create');
        $jqgrid['url_edit'] = site_url($this->router->directory . 'menu/edit');
        $jqgrid['url_delete'] = site_url($this->router->directory . 'menu/delete');

        $this->smarty->assign('jqgrid', $jqgrid);
        $jqgrid_init = $this->smarty->get_contents('template/backend/js/jqgrid');

        $js_text = array($jqgrid_init);
        $this->smarty->assign('css_files', $css_files);
        $this->smarty->assign('js_files', $js_files);
        $this->smarty->assign('js_text', $js_text);
        $this->smarty->assign('title', $menu->localize_label('manager'));

        // view
        $this->smarty->view('backend/menu/jqgrid', 'grid');
        $this->smarty->display('template/backend/admin');
    }

    /**
     * Create data
     *
     * @access public
     */
    public function create() {

        $menu = new Menu_model();
        $language = new Language_model();    

        $menu_list = array(
        	'0' => '---Menu chính---'
        );
        
        $menu->get_list_title($menu_list, FALSE, 2);
        
        $this->smarty->assign('language', $language);
        $this->smarty->assign('menu', $menu);        
        $this->smarty->assign('menu_list', $menu_list);

        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $this->smarty->view('backend/menu/edit', 'main_content');
            $this->smarty->display('template/backend/admin');
        } else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required|max_length[150]');

            if ($this->form_validation->run() == TRUE) {
                $menu = new Menu_model();
                $this->_save(site_url('auth/menu'), $menu);
            } else {
                $this->smarty->view('backend/menu/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    public function edit() {
        $menu = new Menu_model();
        $language = new Language_model();
        
        $this->smarty->assign('language', $language);
        
        if ($this->input->server('REQUEST_METHOD') === 'GET') {

            $parameters = $this->uri->ruri_to_assoc(3);

            if (isset($parameters['id'])) {
                $id = intval($parameters['id']);
            } else {
                $id = 0;
            }

            $menu->get_by_id($id);

            if ($menu->exists()) {
                $menu_list = array(
                    '0' => '---Menu chính---'
                );                
                $menu->get_list_title($menu_list, FALSE, 2);
                $this->smarty->assign('menu_list', $menu_list);
                //---------------------end-----------------------------
                $this->smarty->assign('menu', $menu);
                $this->smarty->view('backend/menu/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            } else {
                $this->session->set_flashdata('error_message', $this->lang->line('not_found') /* 'Bài viết này không tồn tại xin vui lòng kiểm tra lại.' */);
                redirect(site_url('auth/menu'));
            }
        } else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required|max_length[150]');

            $id = $this->input->post('id');
            $menu->get_by_id($id);

            if ($this->form_validation->run() == TRUE) {
                $this->_save(site_url('auth/menu/'), $menu);
            } else {
                $this->smarty->assign('menu', $menu);
                $this->smarty->view('backend/menu/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    private function _save($uri, $menu) {
        // Begin transaction
        $menu->trans_begin();

        $this->load->helper('news');

        $menu->title = $this->input->post('title');
        $menu->code = alias_name($menu->title);
        $menu->link = $this->input->post('link');
        $menu->new_page = $this->input->post('new_page');
        $menu->image = $this->input->post('image');
        $menu->type = $this->input->post('type');
        $menu->position = $this->input->post('position');
        $menu->parent_id = intval($this->input->post('parent_id'));
        $menu->order = intval($this->input->post('order'));
        $menu->active = $this->input->post('active');
        $menu->language_id = $this->input->post('lang_id');

        $user = $this->login_manager->get_user();

        $now = date("Y:m:d H:i:s");

        if (!isset($menu->id)) {
            //created
            $menu->created = $now;
            $menu->creator_id = $user->id;
        } else {
            //edit
            $menu->updated = $now;
            $menu->editor_id = $user->id;
        }

        $menu->save();
        $exists = $menu->exists();
        // Attempt to save user
        // Check status of transaction
        if ($menu->trans_status() === FALSE) {
            // Transaction failed, rollback
            $menu->trans_rollback();

            // Add error message
            $u->error_message('transaction', 'The transaction failed to save (insert)');
        } else {
            // Transaction successful, commit
            $menu->trans_commit();

            if ($exists) {
                $this->session->set_flashdata('message', $menu->localize_label('edit_success') /* 'Đã cập nhật dữ liệu thành công.' */);
            } else {
                $this->session->set_flashdata('message', $menu->localize_label('create_success') /* 'Đã lưu dữ liệu thành công.' */);
            }
            redirect($uri);
        }
        // Show all errors
        $error = $menu->error->string;

        $this->session->set_flashdata('message', $error);
        edirect($uri);
    }

    function ajax_parent() {
        if (IS_AJAX) {
            $menu_id = intval($this->uri->rsegment(3));
            $type = trim($this->uri->rsegment(4));
            $menu = new Menu_model();

            if (!in_array($type, $menu->type_list())) {
                echo 'Error! Menu type';
                exit;
            }

            if ($menu_id > 0) {
                $menu->where('id', $menu_id);
                $menu->get(1);
                if ($menu->id <= 0) {
                    echo 'Error! Menu ID';
                    exit;
                }
            }
            $menu_list = array(0 => $this->lang->line('root_menu'));
            $menu->get_list_title($menu_list, TRUE, 2, $this->language_manager->get_language()->id, $type);
            $this->smarty->assign('option_list', $menu_list);
            $this->smarty->display('backend/menu/ajax_option');
        }
    }

    /**
     * init function, get para for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsoninit() {
        if (IS_AJAX) {
            $menu = new Menu_model();
            $metadata = $menu->jqgrid_metadata();
            echo json_encode($metadata);
        }
    }

    /**
     * data function, get data for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsondata() {
        if (IS_AJAX) {
            $search = $this->input->post('_search');
            $filters = json_decode($this->input->post('filters'));
            $order = $this->input->post('sidx');
            $order_direct = $this->input->post('sord');
            $page = intval($this->input->post('page'));
            $num_per_page = intval($this->input->post('rows'));

            $relative_search = array();

            $this->load->helper('jqgrid');

            $menu = jqgrid_search(new Menu_model(), $search, $filters, $order, $order_direct, $page, $num_per_page, $relative_search);

            $paged = $menu->paged;
            $responce = new Stdclass();
            $responce->page = $paged->current_page; //curent page
            $responce->total = $paged->total_pages; //total page
            $responce->records = $paged->total_rows; //total record
            $i = 0;

            $responce = new Stdclass();
            $responce->page = $paged->current_page; //curent page
            $responce->total = $paged->total_pages; //total page
            $responce->records = $paged->total_rows; //total record
            $i = 0;

            foreach ($menu as $item) {
                $isLeaf = TRUE;
                if ($item->parent_id <= 0)
                    $parent = 'Menu chính';
                else {
                    $menu = new Menu_model();
                    $menu->select('id, title');
                    $menu->where('id', $item->parent_id);
                    $menu->get(1);
                    $parent = $menu->title;
                }

                $responce->rows[$i]['cell'] = array(
                    // Field
                    $item->id,
                    $item->title,
                    $item->link,
                    $item->get_new_page(),
                    $item->get_type(),
                    $item->order,
                    $item->get_active(),
                    $parent,
                    $item->get_position(),
                    // Format
                    NULL,
                    NULL,
                    $isLeaf,
                    false
                );
                $i++;
            }
            echo json_encode($responce);
        }
    }

    /**
     * delete function, delete exists object
     *
     * @access public
     * @param id of object in url
     * @return void
     */
    function delete() {

        $url = 'menu';
        $parameters = $this->uri->ruri_to_assoc();
        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
        } else {
            $id = 0;
        }
        if ($id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('no_access_direct'));
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }
        $menu = new Menu_model();
        $menu->where('id', $id);
        $menu->get(1);
        if ($menu->id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('invalide_id'));
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }

        $result = $menu->delete();
        if ($result === TRUE) {
            $this->session->set_flashdata('message', $menu->localize_label('delete_success'));
        } else {
            if ($result == -1) {
                $this->session->set_flashdata('message', $menu->localize_label('delete_submenu_first'));
            } else {
                $this->session->set_flashdata('message', $menu->localize_label('delete_fail'));
            }
        }
        redirect($this->router->directory . $url);
    }

}

/* End of file menu.php */
/* Location: ./system/application/controllers/backend/menu.php */